<template>
  <div>
    <div v-if="mode === 'DESIGN'">
      <el-button size="small" icon="el-icon-paperclip" round>选择文件</el-button>
     <!-- <ellipsis :row="1" :content="placeholder + sizeTip" hoverTip slot="tip" class="el-upload__tip" /> -->
    </div>
    <div v-else>
    <!--  {{formDisabled}} -->
      <el-upload :file-list="fileList" action="#" :limit="maxSize" with-credentials :multiple="maxSize > 0"
        :data="uploadParams" :before-upload="beforeUpload" :http-request="requestUpload" :show-file-list="false">
        <el-button size="small" icon="el-icon-paperclip" round>选择文件</el-button>
        <!-- <ellipsis :row="1" :content="placeholder" hoverTip slot="tip" class="el-upload__tip" /> -->
      </el-upload>
      <el-row type="flex" justify="center">
        <div style="width:100%">
          <div class="fileTemp" v-for="file in fileList" :key="file.uid">
            <div class="fileTemp_left" @click="handlePictureCardPreview(file)">
              <i class="el-icon-document" style="margin-right: 5px"></i>
              {{ file.name }}
            </div>
            <div class="right_icon">
              <span style="margin-right:25px;" @click="downloadHandle(file)"><i class="el-icon-download"></i></span>
              <span v-if="!formDisabled" @click="handleRemove(file)"><i class="el-icon-circle-close"></i></span>
            </div>
          </div>
        </div>
      </el-row>
    </div>
  </div>
</template>

<script>
  import componentMinxins from '../ComponentMinxins';
  import {
    uploadAction,
    getFileAccessHttpUrl,
    downloadFile
  } from '@/api/manage'
  // import Ellipsis from '@/components/wflow/Ellipsis'
   import { Base64 } from 'js-base64'
  const uidGenerator = () => {
    return '-' + parseInt(Math.random() * 10000 + 1, 10);
  }
  const getFileName = (path) => {
    if (path.lastIndexOf("\\") >= 0) {
      let reg = new RegExp("\\\\", "g");
      path = path.replace(reg, "/");
    }
    return path.substring(path.lastIndexOf("/") + 1);
  }
  export default {
    mixins: [componentMinxins],
    name: 'FileUpload',
    components: { },
    props: {
      placeholder: {
        type: String,
        default: '请选择附件',
      },
      value: {
        type: [String, Array],
        required: false
      },
      maxSize: {
        type: Number,
        default: 5,
      },
      maxNumber: {
        type: Number,
        default: 10,
      },
      fileTypes: {
        type: Array,
        default: () => {
          return [];
        },
      },
      mode: {
        type: String,
        default: 'DESIGN'
      },
      required: {
        type: Boolean,
        default: false
      },
      disabled:{
        type:Boolean,
        default:false
      },
    },
    computed: {
      sizeTip() {
        if (this.fileTypes.length > 0) {
          return ` | 只允许上传[${String(this.fileTypes).replaceAll(',', '、')}]格式的文件，且单个附件不超过${this.maxSize}MB`;
        }
        return this.maxSize > 0 ? ` | 单个附件不超过${this.maxSize}MB` : '';
      },
    },
    watch: {
      value: {
        handler(val, oldValue) {
          if (val instanceof Array) {
            this.initFileList(val.join(','))
          } else {
            this.initFileList(val)
          }
          if (!val || val.length == 0) {
            this.picUrl = false;
          }
        },
        //立刻执行handler
        immediate: true
      }
    },
    data() {
      return {
        uploadParams: {},
        fileList: [] 
      };
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    methods: {
      initFileList(paths) {
        if (!paths || paths.length == 0) {
          this.fileList = [];
          return;
        }
        this.picUrl = true;
        let fileList = [];
        let arr = paths.split(",")
        for (var a = 0; a < arr.length; a++) {
          let url = getFileAccessHttpUrl(arr[a]);
          fileList.push({
            uid: uidGenerator(),
            name: getFileName(arr[a]),
            status: 'done',
            url: url
          })
        }
        this.fileList = fileList
      },
      // 覆盖默认的上传行为
      requestUpload(data) {
        if (data.file) {
          //上传文件的需要formdata类型;所以要转
          let FormDatas = new FormData();
          FormDatas.append('file', data.file);
          uploadAction(window._CONFIG['domianURL'] + '/file/upload', FormDatas).then((res) => {
            if (res.success) {   
              // this.urlList=[]
              let urlList = []
              if (res.message) {
                this.fileList.push({
                  name: data.file.name,
                  url: res.message
                })
                if (this.fileList && this.fileList.length > 0) {
                  this.fileList.forEach((item) => {
                    urlList.push(item.url)
                  })
                  this.$emit('change', urlList.join(','))
                  this._value = urlList.join(',')
                } else {
                  this.$emit('change', null)
                  this._value = null
                }
              } else {
                this.$message.warning(res.message);
              }
            }
          })
        }
      },
      beforeUpload(file) {
        if (this.maxSize > 0 && file.size / 1024 / 1024 > this.maxSize) {
          this.$message.warning(`单张图片最大不超过 ${this.maxSize}MB`);
          return false;
        }
      },
      //删除
      handleRemove(file, fileList) {
        const fileData = this.fileList
        let urlList = []
        if(file){
          const index = fileData.findIndex((s)=>s.url === file.url)
          this.fileList.splice(index,1)
          if(this.fileList && this.fileList.length > 0){
            this.fileList.forEach((item)=>{
               urlList.push(item.url)
            })
            this.$emit('change',urlList.join(','))
            this._value = urlList.join(',')
          }
        }
      },
      //预览
      handlePictureCardPreview(file) {
        let base = `${window._CONFIG['onlinePreviewDomainURL']}?url=`
        let url = base+encodeURIComponent(Base64.encode(file.url))
        window.open(url, '_blank')
      },
      //下载
      downloadHandle(file) {
        var a = document.createElement('a')
        a.href = file.url
        a.download = file.url
        a.target = '_blank';
        a.style.display = 'none'
        document.body.appendChild(a)
        a.click()
        a.remove()
      },
    },
    model: {
      prop: 'value',
      event: 'change'
    }
  };
</script>

<style lang="less" scoped>
  /deep/.el-upload{
    width: 100%;
    text-align: left;
  }
  /deep/.el-upload__tip{
    margin-top: 0;
  }
  .fileTemp {
    margin:0;
    padding: 0 15px;
    border-radius: 8px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    cursor: pointer;
    transition: .6s;
    .fileTemp_left{
      width: calc(100% - 100px);
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .right_icon{
      font-size: 16px;  
      display: none;
    }
  }
  .fileTemp:hover{
    background-color:#f5f7fa;
    color: #409eff;
  }
  .fileTemp:hover .right_icon{
    display: block;
  }
</style>